﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using YuuzleComic.DALFactory;
using System.Net;
using YuuzleComic.Common;
using System.Text.RegularExpressions;

public partial class yzadmin_data_collect_hhcomic : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private string domain = "http://www.hhcomic.com";
    private string baseUrl = "http://www.hhcomic.com/comicupdate/";
    private string baseUrl1 = "http://www.hhcomic.com/hh/";
    private string searchUrl = "http://www.baidu.com/s?wd={0}&pn={1}&ct=2097152&si=hhcomic.com&sts=hhcomic.com";
    private string jsUrl = "http://www.hhcomic.com/hh/hhh.js";

    private JObject result = new JObject();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            string js = new WebClient().DownloadString(jsUrl);
            List<string> serverList = new List<string>();//ServerList[0]="http://58.51.95.66:9898/dm01/";
            MatchCollection collection = Regex.Matches(js, @"ServerList\[\d+\]\=""([a-zA-z]+://[^\s]*)"";");
            foreach (Match match in collection)
            {
                serverList.Add(match.Groups[1].Value);
            }
            DataCache.SetCache("refererDomain", domain + "/");//破解防盗链域名
            DataCache.SetCache("refererServerList", serverList);//破解防盗链服务器列表
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                string[] tpArr = doc.DocumentNode.SelectSingleNode("//script[@language='javascript']").InnerText.Split(new string[] { "= \"", "\";" }, StringSplitOptions.None)[1].Trim().Split('|');
                int sIndex = int.Parse(url.Split(new string[] { ".htm?s=" }, StringSplitOptions.None)[1]);
                List<string> tpurl = new List<string>();
                foreach (string tp in tpArr)
                {
                    tpurl.Add(serverList[sIndex - 1] + tp);
                }

                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                string zjmc = doc.DocumentNode.SelectSingleNode("//*[@id='all']/div[2]/a[1]").InnerText;
                zj.zjmc = Request["mhmc"] != null ? zjmc.Replace(Request["mhmc"], "") : zjmc;
                zj.zjmc = zj.zjmc.Replace(" ", "").Replace("集", "话").Trim();
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode infoNode = doc.DocumentNode.SelectSingleNode("//*[@id='content']");
            HtmlNodeCollection attrNodes = infoNode.SelectNodes("div//div[starts-with(@class,'sectioninfo')]/p");
            string[] mhmcmhzz = infoNode.SelectSingleNode("div[2]/table/tr[1]/td[2]").InnerText.Split(new string[] { "内容介绍 作者：" }, StringSplitOptions.None);
            result.Add("mhmc", mhmcmhzz[0].Trim());
            result.Add("mhfm", infoNode.SelectSingleNode("div[2]/table/tr[1]/td[1]/img").Attributes["src"].Value);
            result.Add("zzmc", mhmcmhzz[1].Trim());
            result.Add("zt", infoNode.SelectSingleNode("div[1]/font[2]").InnerText);
            result.Add("mhjj", infoNode.SelectSingleNode("div[2]/table/tr[2]/td/div").InnerText.Trim());
            result.Add("mhjs", infoNode.SelectSingleNode("div[2]/table/tr[2]/td/div").InnerHtml);
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = infoNode.SelectNodes("div[@class='vol']/ul/li");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.SelectSingleNode("a").InnerText);
                    chapter.Add("zjurl", domain + item.SelectSingleNode("a").Attributes["href"].Value);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            JArray data = new JArray();
            if (Request["query"] == null || string.IsNullOrEmpty(Request["query"].Trim()))
            {
                HtmlDocument doc = webClient.Load(baseUrl);
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[@id='content']/div[2]/table[@cellpadding='0']");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("tr/td[1]/a").InnerText);
                    jo.Add("mhurl", domain + node.SelectSingleNode("tr/td[1]/a").Attributes["href"].Value);
                    jo.Add("zjmc", node.SelectSingleNode("tr/td[1]/font/b") != null ? node.SelectSingleNode("tr/td[1]/font/b").InnerText : "");
                    jo.Add("zt", node.SelectSingleNode("tr/td[1]/span").InnerText);
                    jo.Add("time", node.SelectSingleNode("tr/td[2]").InnerText);
                    data.Add(jo);
                }
                doc = webClient.Load(baseUrl1);
                nodes = doc.DocumentNode.SelectNodes("//*[@id='content']/div[4]/div[@class='l22']");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("div[1]/a").InnerText);
                    jo.Add("mhurl", domain + node.SelectSingleNode("div[1]/a").Attributes["href"].Value);
                    data.Add(jo);
                }
                result.Add("total", data.Count);
            }
            else
            {
                HtmlDocument doc = webClient.Load(string.Format(searchUrl, new string[] { Request["query"].Trim(), Request["start"] }));
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[@id='container']/table[@class='result']");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("tr/td/h3/a").InnerText);
                    jo.Add("mhurl", node.SelectSingleNode("tr/td/h3/a").Attributes["href"].Value);
                    data.Add(jo);
                }
                result.Add("total", Input.GetNumberInt(doc.DocumentNode.SelectSingleNode("//*[@id='page']/span").InnerText));
            }
            result.Add("data", data);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = new System.Net.CookieContainer();
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}